package logic

import (
	"context"
	"yuanxin-admin/internal/dto"
	"yuanxin-admin/internal/model"
	"yuanxin-admin/internal/repository"
	"yuanxin-admin/internal/service"

	"gitee.com/botaoshow/yuanxin/web/common/database"
)

func NewSysDictDictService() service.ISysDictService {
	return &SysDictServiceImpl{}
}

type SysDictServiceImpl struct {
}

func (s SysDictServiceImpl) Create(c context.Context, d *dto.SysDictDTO) (bool, error) {
	q := repository.Use(database.Db)
	// 开启事务
	err := q.Transaction(func(tx *repository.Query) error {
		var sysDict = model.SysDict{
			Code:   d.Code,
			Name:   d.Name,
			Type:   d.Type,
			Status: d.Status,
		}
		// 在事务中创建主表记录
		err := tx.SysDict.WithContext(c).Create(&sysDict)
		if err != nil {
			return err // 回滚事务
		}

		// 获取生成的 ID 并创建子表记录
		var subs []*model.SysDictOption
		for _, v := range d.Children {
			var sysDictOption = &model.SysDictOption{
				Label:    v.Label,
				ParentID: v.ParentID,
				Sort:     v.Sort,
				Status:   v.Status,
				TypeID:   sysDict.ID, // 使用生成的主键ID
				Value:    v.Value,
			}
			subs = append(subs, sysDictOption)
		}

		// 批量创建子表记录
		if len(subs) > 0 {
			err := tx.SysDictOption.WithContext(c).CreateInBatches(subs, 100)
			if err != nil {
				return err // 回滚事务
			}
		}

		return nil // 提交事务
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func (s SysDictServiceImpl) Update(c context.Context, id int64, d *dto.SysDictDTO) (bool, error) {
	var sysDict = &model.SysDict{
		Code:   d.Code,
		Name:   d.Name,
		Type:   d.Type,
		Status: d.Status,
	}
	updates, err := repository.SysDict.WithContext(c).Where(repository.SysDict.ID.Eq(id)).Updates(sysDict)
	if err != nil {
		return false, err
	}
	return updates.RowsAffected > 0, nil
}
